package com.wpp.data_structure.queue;

import com.wpp.data_structure.MyNode;

/**
 * @author wpp25
 * @date 2021/6/3 20:45
 * @description：
 */
public class DefaultQueue<T>  implements MyQueue<T>{

    private MyNode<T> head;

    private MyNode<T> tail;

    private int size;

    @Override
    public String print() {
        StringBuilder sb = new StringBuilder("队列头部 <- ");
        if (head != null) {
            MyNode<T> currentNode = head;
            sb.append(currentNode.element).append(" ");
            while (currentNode.next != null) {
                sb.append(currentNode.next.element).append(" ");
                currentNode = currentNode.next;
            }
        }

        sb.append(" <- 队列尾部 size：").append(size);
        return sb.toString();
    }

    @Override
    public void add(T t) {
        MyNode<T> node = new MyNode<>(t);
        if (tail == null) {
            tail = head = node;
        } else{
            tail.next = node;
            node.pre = tail;
            tail = node;
        }
        size++;
    }

    @Override
    public T poll() {
        if (size == 0) {
            throw new IllegalArgumentException("queue is empty");
        }
        T ele = head.element;
        if (head.next != null) {
            head = head.next;
            head.pre = null;
        } else {
            head = null;
            tail = null;
        }
        size--;
        return ele;
    }

    @Override
    public T top() {
        if (size == 0) {
            return null;
        }
        return head.element;
    }

    @Override
    public T tail() {
        if (size == 0) {
            return null;
        }
        return tail.element;
    }

    @Override
    public int getSize() {
        return size;
    }
}
